﻿(function ($) {
    $.fn.jquizzy = function (settings) {
        var defaults = {
            questions: null,
            endText: '已结束!',
            shortURL: null,
            sendResultsURL: null,
            resultComments: {
                perfect: '你是爱因斯坦么?',
                excellent: '非常优秀!',
                good: '很好，发挥不错!',
                average: '一般般了。',
                bad: '太可怜了！',
                poor: '好可怕啊！',
                worst: '悲痛欲绝！'
            }
        };
        // 合并settings参数值到defaults
        var config = $.extend(defaults, settings);
        //如果questions没有初始化成功,则报错!
        if (config.questions === null) {
            $(this).html('<div class="intro-container slide-container"><h2 class="qTitle">Failed to parse questions.</h2></div>');
            return;
        }

        var superContainer = $(this),
            answers = [],
        //结束页面html代码
            exitFob = '<div class="results-container slide-container">' +
                // '<div class="question-number">' + config.endText + '</div>' +
                '<div class="result-keeper"></div></div>' +
                '<div class="notice text-danger panel-footer">请选择一个选项！</div>' +
                '<div class="progress-keeper" ><div class="progress"></div></div>',
        //div的内容
            contentFob = '',
        //第几个问题
            questionsIteratorIndex,
        //第几个答案
            answersIteratorIndex;
        //添加主要样式
        // superContainer.addClass('main-quiz-holder');

        // $(".panel-heading").html(config.questions[questionsIteratorIndex].question);
        for (questionsIteratorIndex = 0; questionsIteratorIndex < config.questions.length; questionsIteratorIndex++) {
            //配置第几题显示
            //配置题目
            contentFob += '<div class="slide-container panel panel-default">' +
                '<div class="panel-heading text-left">' +
                '<span class=".label label-info">' + (questionsIteratorIndex + 1) + '/' + config.questions.length + '</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'
                + config.questions[questionsIteratorIndex].question + '</div>' +
                '<div class="answers">';
            //显示备选答案
            for (answersIteratorIndex = 0; answersIteratorIndex < config.questions[questionsIteratorIndex].answers.length; answersIteratorIndex++) {
                contentFob += '<button type="button" class="btn btn-primary btn-lg btn-block">' + config.questions[questionsIteratorIndex].answers[answersIteratorIndex] + '</button>';
            }
            contentFob += '</div><div class="nav-container text-center">';
            //如果不是第一题了,就提供"上一题"的按钮
            if (questionsIteratorIndex !== 0) {
                contentFob += '<div class="prev pagination panel-footer"><a class="nav-previous" href="#">&lt; 上一题</a></div>&nbsp;&nbsp;&nbsp;&nbsp;';
            }
            //如果不是最后一题,就提供下一题按钮(or完成)
            if (questionsIteratorIndex < config.questions.length - 1) {
                contentFob += '&nbsp;&nbsp;&nbsp;&nbsp;<div class="next pagination panel-footer"><a href="#">下一题 &gt;</a></div>';
            } else {
                contentFob += '&nbsp;&nbsp;&nbsp;&nbsp;<div class="next final pagination panel-footer"><a href="#">完成</a></div>';
            }
            contentFob += '</div></div>';
            //添加正确答案到数组
            answers.push(config.questions[questionsIteratorIndex].correctAnswer);
        }
        // superContainer.html(introFob + contentFob + exitFob);
        superContainer.html(contentFob + exitFob);
        var progress = superContainer.find('.progress'),
            progressKeeper = superContainer.find('.progress-keeper'),
            notice = superContainer.find('.notice'),
            progressWidth = progressKeeper.width(),
            userAnswers = [],
            questionLength = config.questions.length,
            slidesList = superContainer.find('.slide-container');

        // 检查答案
        function checkAnswers() {
            var resultArr = [],
                flag = false;
            for (i = 0; i < answers.length; i++) {
                if (answers[i] == userAnswers[i]) {
                    flag = true;
                } else {
                    flag = false;
                }
                resultArr.push(flag);
            }
            return resultArr;
        }

        function roundReloaded(num, dec) {
            var result = Math.round(num * Math.pow(10, dec)) / Math.pow(10, dec);
            return result;
        }

        //计算分数
        function judgeSkills(score) {
            var returnString;
            if (score === 100) return config.resultComments.perfect;
            else if (score > 90) return config.resultComments.excellent;
            else if (score > 70) return config.resultComments.good;
            else if (score > 50) return config.resultComments.average;
            else if (score > 35) return config.resultComments.bad;
            else if (score > 20) return config.resultComments.poor;
            else return config.resultComments.worst;
        }

        progressKeeper.hide();
        notice.hide();
        slidesList.hide().first().fadeIn(500);
        //选中的CSS
        superContainer.find('button').click(function () {
            var thisLi = $(this);
            if (thisLi.hasClass('btn-default')) { //点击 当前选中的按钮
                thisLi.removeClass('btn-default');
                thisLi.addClass('btn-primary');
            } else { //点击 未选中的按钮
                thisLi.parents('.answers').children('button').removeClass('btn-default');
                thisLi.parents('.answers').children('button').addClass('btn-primary');
                thisLi.removeClass('btn-primary');
                thisLi.addClass('btn-default');
            }
        });
        superContainer.find('.nav-start').click(function () {
            $(this).parents('.slide-container').fadeOut(500,
                function () {
                    $(this).next().fadeIn(500);
                    progressKeeper.fadeIn(500);
                });
            return false;
        });
        //动作 下一题
        superContainer.find('.next').click(function () {
            alert($(this).parents('.answers').children('button').index($(this).parents('.answers').find('button.btn-default')) + 1);
            if ($(this).parents('.slide-container').find('button.btn-default').length === 0) {
                notice.fadeIn(300);
                return false;
            }
            notice.hide();
            $(this).parents('.slide-container').fadeOut(500,
                function () {
                    $(this).next().fadeIn(500);
                });
            progress.animate({
                    width: progress.width() + Math.round(progressWidth / questionLength)
                },
                500);
            return false;
        });
        //动作 上一题
        superContainer.find('.prev').click(function () {
            notice.hide();
            $(this).parents('.slide-container').fadeOut(500,
                function () {
                    $(this).prev().fadeIn(500);
                });
            progress.animate({
                    width: progress.width() - Math.round(progressWidth / questionLength)
                },
                500);
            return false;
        });
        //答题完毕,统计数据
        superContainer.find('.final').click(function () {
            if ($(this).parents('.slide-container').find('button.btn-default').length === 0) {
                notice.fadeIn(300);
                return false;
            }
            superContainer.find('button.btn-default').each(function (index) {
                userAnswers.push($(this).parents('.answers').children('button').index($(this).parents('.answers').find('button.btn-default')) + 1);
            });
            if (config.sendResultsURL !== null) {
                var collate = [];
                for (r = 0; r < userAnswers.length; r++) {
                    collate.push('{"questionNumber":"' + parseInt(r + 1, 10) + '", "userAnswer":"' + userAnswers[r] + '"}');
                }
                $.ajax({
                    type: 'POST',
                    url: config.sendResultsURL,
                    data: '{"answers": [' + collate.join(",") + ']}',
                    complete: function () {
                        console.log("OH HAI");
                    }
                });
            }
            progressKeeper.hide();
            var results = checkAnswers(),
                resultSet = '',
                trueCount = 0,
                shareButton = '',
                score,
                url;
            if (config.shortURL === null) {
                config.shortURL = window.location
            }
            ;
            for (var i = 0,
                     toLoopTill = results.length; i < toLoopTill; i++) {
                if (results[i] === true) {
                    trueCount++;
                    isCorrect = true;
                }
                resultSet += '<div class="result-row list-group-item">' +
                    (results[i] === true ? "<h3 class='label label-success'>题目" + (i + 1) + "</h3>"
                    + "<span class='glyphicon glyphicon-ok'></span>&nbsp;&nbsp;&nbsp;"
                    + config.questions[i].question + "</div>"//+ " - <span class='badge'>正确答案:</span>"
                    // + config.questions[i].answers[config.questions[i].correctAnswer - 1] + "</div>"
                        : "<h3 class='label label-danger'>题目" + (i + 1) + "</h3>" +
                    "<span class='glyphicon glyphicon-remove'></span>&nbsp;&nbsp;&nbsp;"
                    + config.questions[i].question + "<span class='badge'>"
                    + config.questions[i].answers[config.questions[i].correctAnswer - 1] + "</span></div>");
                // resultSet += '<div class="resultsview-qhover">' + config.questions[i].answers[config.questions[i].correctAnswer - 1];
                // resultSet += '<div>' + config.questions[i].answers[config.questions[i].correctAnswer - 1];
                // resultSet += "<ul>";
                // for (answersIteratorIndex = 0; answersIteratorIndex < config.questions[i].answers.length; answersIteratorIndex++) {
                //     var classestoAdd = '';
                //     if (config.questions[i].correctAnswer == answersIteratorIndex + 1) {
                //         classestoAdd += 'right';
                //     }
                //     if (userAnswers[i] == answersIteratorIndex + 1) {
                //         classestoAdd += ' selected';
                //     }
                //     resultSet += '<li class="' + classestoAdd + '">' + config.questions[i].answers[answersIteratorIndex] + '</li>';
                // }
                // resultSet += '</ul></div></div>';
            }
            score = roundReloaded(trueCount / questionLength * 100, 2);

            resultSet = '<div class="panel-heading"><h1>' + judgeSkills(score) + '&nbsp;&nbsp;&nbsp;<small>您的分数： ' + score + '</small></h1></div>' + shareButton + '<div class="jquizzy-clear"></div>' + resultSet + '<div class="jquizzy-clear"></div>';
            superContainer.find('.result-keeper').html(resultSet).show(500);
            superContainer.find('.resultsview-qhover').hide();
            //xianshi
            superContainer.find('.result-row').hover(function () {
                    $(this).find('.resultsview-qhover').show();
                },
                function () {
                    $(this).find('.resultsview-qhover').hide();
                });
            $(this).parents('.slide-container').fadeOut(500,
                function () {
                    $(this).next().fadeIn(500);
                });
            return false;
        });
    };
})(jQuery);